package nachos.threads;

import nachos.machine.*;

/**
 * An implementation of condition variables that disables interrupt()s for
 * synchronization.
 *
 * <p>
 * You must implement this.
 *
 * @see	nachos.threads.Condition
 */
public class Condition2 {
    /**
     * Allocate a new condition variable.
     *
     * @param	conditionLock	the lock associated with this condition
     *				variable. The current thread must hold this
     *				lock whenever it uses <tt>sleep()</tt>,
     *				<tt>wake()</tt>, or <tt>wakeAll()</tt>.
     */
    private ThreadQueue waitQueue;

    public Condition2(Lock conditionLock) {
        this.waitQueue = ThreadedKernel.scheduler.newThreadQueue(false);
	this.conditionLock = conditionLock;
    }

    /**
     * Atomically release the associated lock and go to sleep on this condition
     * variable until another thread wakes it using <tt>wake()</tt>. The
     * current thread must hold the associated lock. The thread will
     * automatically reacquire the lock before <tt>sleep()</tt> returns.
     */
    public void sleep() {
	boolean prevStatus = Machine.interrupt().disable();
        
        Lib.assertTrue(conditionLock.isHeldByCurrentThread());

        this.waitQueue.waitForAccess(KThread.currentThread());

	conditionLock.release();

        KThread.sleep();

	conditionLock.acquire();
        Machine.interrupt().restore(prevStatus);
    }

    /**
     * Wake up at most one thread sleeping on this condition variable. The
     * current thread must hold the associated lock.
     */
    public void wake() {
	Lib.assertTrue(conditionLock.isHeldByCurrentThread());
        try{
            boolean state = Machine.interrupt().disable();
            this.waitQueue.nextThread().ready();
            Machine.interrupt().restore(state);
        } catch (NullPointerException e){
            //nothing we only do this
        }
    }

    /**
     * Wake up all threads sleeping on this condition variable. The current
     * thread must hold the associated lock.
     */
    public void wakeAll() {
	KThread wakeable;
        Lib.assertTrue(conditionLock.isHeldByCurrentThread());
        boolean state = Machine.interrupt().disable();
        while((wakeable = waitQueue.nextThread()) != null )
            wakeable.ready();
        Machine.interrupt().restore(state);
    }

    private Lock conditionLock;
}
